<template>
  <el-dialog
    :title="info.isadd ? '添加商品管理' : '编辑商品管理'"
    :visible.sync="info.isshow"
    center
    :before-close="cancel"
    @opened = "opened"
  >
    <el-form :model="goodsinfo" :rules="rules" ref="form">
      <!-- 一级分类 -->
      <el-form-item label="一级分类" label-width="120px" prop="first_cateid">
        <el-select v-model="goodsinfo.first_cateid" placeholder="请选择" @change="changeFirst">
          <el-option
            v-for="item in get_cateList"
            :key="item.id"
            :label="item.catename"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 二级分类 -->
      <el-form-item label="二级分类" label-width="120px" prop="second_cateid">
        <el-select v-model="goodsinfo.second_cateid" placeholder="请选择">
          <el-option
            v-for="item in secondArr"
            :key="item.id"
            :label="item.catename"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 商品名称 -->
      <el-form-item label="商品名称" label-width="120px" prop="goodsname">
        <el-input v-model="goodsinfo.goodsname"></el-input>
      </el-form-item>
      <!-- 价格 -->
      <el-form-item label="价格" label-width="120px" prop="price">
        <el-input v-model.number="goodsinfo.price"></el-input>
      </el-form-item>
      <!-- 市场价格 -->
      <el-form-item label="市场价格" label-width="120px" prop="market_price">
        <el-input v-model.number="goodsinfo.market_price"></el-input>
      </el-form-item>

      <!-- 图片 -->
      <el-form-item label="图片" label-width="120px">
         <!-- 上传图片 -->
        <!-- action:上传地址，我们是要发请求上传 用# 
             list-type：文件列表的类型
             auto-upload：自动上传 默认是true

             on-preview：点击文件列表中已上传的文件时的钩子 
             on-remove：文件列表移除文件时的钩子   
             on-change:文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
        -->
        <el-upload
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :file-list='filelist'
          :on-preview="onpreview"
          :on-remove="onremove"
          :on-change="onchange"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" :modal-append-to-body="false" :append-to-body="true">
          <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
      </el-form-item>

      <!-- 商品规格 -->
      <el-form-item label="商品规格" label-width="120px" prop="specsid">
        <el-select v-model="goodsinfo.specsid" placeholder="请选择" @change="changeSpecs">
          <el-option
            v-for="item in get_specsList"
            :key="item.id"
            :label="item.specsname"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 商品规格属性 -->
      <el-form-item label="商品规格属性" label-width="120px" prop="specsattr">
        <el-select v-model="goodsinfo.specsattr" multiple placeholder="请选择">
          <el-option v-for="item in secondSpecsArr" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>

      <!-- 是否新品 -->
      <el-form-item label="是否新品" label-width="120px">
        <el-radio v-model="goodsinfo.isnew" :label="1">是</el-radio>
        <el-radio v-model="goodsinfo.isnew" :label="2">否</el-radio>
      </el-form-item>

      <!-- 是否热卖 -->
      <el-form-item label="是否热卖" label-width="120px">
        <el-radio v-model="goodsinfo.ishot" :label="1">是</el-radio>
        <el-radio v-model="goodsinfo.ishot" :label="2">否</el-radio>
      </el-form-item>

      <!-- 状态 -->
      <el-form-item label="状态" label-width="120px">
        <el-switch
          v-model="goodsinfo.status"
          active-color="#13ce66"
          inactive-color="#ff4949"
          :active-value="1"
          :inactive-value="2"
        ></el-switch>
      </el-form-item>

      <!-- 描述 -->
      <el-form-item label="描述" label-width="120px">
        <!-- 第三步：在需要使用富文本编辑器的地方定义div并设置id -->
        <div id="description"></div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="sure">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import { goodsadd, goodsinfo, goodsedit } from "@/request/api.js";
// 第一步：下载
// 第二步：引入
import wangEditor from 'wangeditor'

export default {
  props: ["info"],
  data() {
    //自定义规则
    let price = (rule, value, callback) => {
      //一定是数字， 而且不能是负数
      if (typeof value != "number") {
        callback(new Error("价格必须是一个数字"));
        return;
      }

      if (value < 0) {
        callback(new Error("请输入正确的价格"));
        return;
      }

      callback();
    };
    return {
      //商品数据
      goodsinfo: {
        first_cateid: "", //一级分类编号
        second_cateid: "", //二级分类编号
        goodsname: "", //商品名称
        price: "", //商品价格
        market_price: "", //市场价格
        img: "", //商品图片（文件）
        description: "", //商品描述
        specsid: "", //商品规格编号
        specsattr: [""], //商品规格属性（字符串格式）
        isnew: 1, //是否新品     1-是 2-否
        ishot: 1, //是否热卖推荐 1-是 2-否
        status: 1 //状态1正常2禁用
      },
      //二级分类数据
      secondArr: [], //二级分类的数据
      secondSpecsArr: [], //商品规格属性数据的二级联动
      dialogVisible:false,  //控制预览弹框的变量
      dialogImageUrl:"", //预览的图片地址
      filelist:[], //用于回显数据的
      // 表单规则
      rules: {
        first_cateid: [
          { required: true, message: "请选择一级分类", trigger: "change" }
        ],
        second_cateid: [
          { required: true, message: "请选择二级分类", trigger: "change" }
        ],
        goodsname: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ],
        price: [{ required: true, validator: price, trigger: "blur" }],
        market_price: [{ required: true, validator: price, trigger: "blur" }],
        specsid: [
          { required: true, message: "请选择商品规格", trigger: "change" }
        ],
        specsattr: [
          { required: true, message: "请选择商品规格属性", trigger: "change" }
        ]
      }
    };
  },
  methods: {
    ...mapActions("cate", ["action_cateList"]),
    ...mapActions("specs", ["action_specsList"]),
    ...mapActions("goods", ["action_goodsList"]),
    //1.取消  -- 通知父组件，关闭弹框
    cancel() {
      this.$emit("cancel");
      this.reset();
    },
    //2.重置
    reset() {
      //商品数据
      this.goodsinfo = {
        first_cateid: "", //一级分类编号
        second_cateid: "", //二级分类编号
        goodsname: "", //商品名称
        price: "", //商品价格
        market_price: "", //市场价格
        img: "", //商品图片（文件）
        description: "", //商品描述
        specsid: "", //商品规格编号
        specsattr: "", //商品规格属性（字符串格式）
        isnew: 1, //是否新品     1-是 2-否
        ishot: 1, //是否热卖推荐 1-是 2-否
        status: 1 //状态1正常2禁用
      };
      //二级分类数据
      this.secondArr = []; //二级分类的数据
      this.secondSpecsArr = []; //商品规格属性数据的二级联动
      //清除验证规则
      this.$refs.form.resetFields();
      //销毁富文本
      this.editor.destroy();
      //图片回显清除
      this.filelist = [];
    },
    //3.点击确定
    sure() {
      //先查看一下是否能获取到描述信息
      // console.log(this.editor.txt.html());
      //   return;
      this.$refs.form.validate(async val => {
        if (!val) {
          return;
        }

        
        //添加
        if (this.info.isadd) {
          try {
            this.goodsinfo.description = this.editor.txt.html();
            let res = await goodsadd(this.goodsinfo);
            if (res.code == 200) {
              //提示，关闭弹框，重新渲染页面
              this.$message.success(res.msg);
              this.cancel();
              this.action_goodsList();
            } else {
              this.$message.info(res.msg);
            }
          } catch (err) {
            this.$message.error(err);
          }
        } else {
          try {
            let res = await goodsedit(this.goodsinfo);
            if (res.code == 200) {
              //提示，关闭弹框，重新渲染页面
              this.$message.success(res.msg);
              this.cancel();
              this.action_goodsList();
            } else {
              this.$message.info(res.msg);
            }
          } catch (err) {
            this.$message.error(err);
          }
        }
      });
    },

    //4.选择一级分类后，得到二级分类的数据
    changeFirst(e) {
      //e:一级分类选择的id
      //选对应id的那一个数据
      //  let arr = this.get_cateList.filter(item=>{
      //    return item.id == e
      //  });
      //要的是数据里面的children字段
      //  console.log(arr[0].children);\
      this.goodsinfo.second_cateid = "";
      this.secondArr = this.get_cateList.filter(
        item => item.id == e
      )[0].children;
    },

    //5.二级属性规格
    changeSpecs(e) {
      this.goodsinfo.specsattr = "";
      this.secondSpecsArr = this.get_specsList.filter(
        item => item.id == e
      )[0].attrs;
    },
    //6.数据回显
    async lookup(id) {
      try {
        let res = await goodsinfo({ id });
        if (res.code == 200) {
          //a.数据回显
          this.goodsinfo = res.list;

          //b.添加id字段
          this.goodsinfo.id = id;

          //c.处理二级分类的数据回显
          this.secondArr = this.get_cateList.filter(
            item => item.id == this.goodsinfo.first_cateid
          )[0].children;

          //d.处理二级规格属性数据   要： specsattr=["红色","绿色"]   给的：“红色，绿色”
          this.goodsinfo.specsattr = this.goodsinfo.specsattr.split(",");

          //e.图片回显 this.filelist = [{name:"",url:"图片地址"}]
          //如果有图片就回显，没有图片就是[]不回显
          this.filelist = this.goodsinfo.img ? [{name:"xx.jpg",url: this.$baseUrl + this.goodsinfo.img}]:[];


        } else {
          this.$message.info(res.msg);
        }
      } catch (err) {
        this.$message.error(err);
      }
    },

     //-------图片上传-------
    //预览
    onpreview(file){
      // console.log("预览");
      this.dialogVisible = true;
    },
    onremove(){
      //清空数据
      this.dialogImageUrl = "";
      this.goodsinfo.img = ""
    },
    onchange(file){
      // console.log("选择了图片");
      // console.log("选择了图片",file);
      //给预览图片地址赋值
      this.dialogImageUrl = file.url;
      //给goodsinfo的img赋值 --这张图片要上传
      this.goodsinfo.img = file.raw
    },
    // ----- 富文本相关-------------
    opened(){
      //第四步：实例化富文本  -- 为什么要加到this （this--vue组件实例，组件内任何地方都能用，让其他方法可以使用编辑器）
      this.editor = new wangEditor('#description');

      //第五步：创建富文本
      this.editor.create();

      //回显数据
      this.editor.txt.html(this.goodsinfo.description);
    }
  },
  computed: {
    ...mapGetters("cate", ["get_cateList"]),
    ...mapGetters("specs", ["get_specsList"])
  },
  mounted() {
    //会用到cate分类列表的数据，所以页面挂载完成就要请求数据
    this.get_cateList.length || this.action_cateList();
    this.get_specsList.length || this.action_specsList();
  }
};
</script>

<style>
</style>